package com.vic.dead_letter_queue.max_length;

import com.rabbitmq.client.*;
import com.vic.dead_letter_queue.Consts;
import com.vic.utils.RabbitmqUtils;

import java.util.HashMap;

/**
 * 消费者
 */
public class Consumer01 {

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitmqUtils.getChannel();

        // 声明正常消息的交换机(类型为 direct)
        channel.exchangeDeclare(Consts.NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);

        // 正常队列关联死信交换机（正常队列出现了故障之后,消息就会通过死信交换机传递到死信队列中）
        HashMap<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", Consts.DEAD_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", Consts.DEAD_ROUTING_KEY);
        // 设置正常队列的最大长度
        arguments.put("x-max-length", 3);
        channel.queueDeclare(Consts.NORMAL_QUEUE, true, false, false, arguments);
        // 正常消息交换机绑定正常消息队列
        channel.queueBind(Consts.NORMAL_QUEUE, Consts.NORMAL_EXCHANGE, Consts.NORMAL_ROUTING_KEY, arguments);

        // 消息成功之后的回调
        DeliverCallback deliverCallback = (String consumerTag, Delivery message) -> {
            String msg = new String(message.getBody());
            System.out.println(msg);
        };
        // 取消消费者的回调
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("取消消费者时的回调接口");
        };
        // 消费者消费消息
        channel.basicConsume(Consts.NORMAL_QUEUE, true, deliverCallback, cancelCallback);

        System.out.println("Consumer01 开始消费消息");
    }


}
